<template>
  <div class="custom-link">
    <el-select
      v-model="keywords"
      multiple
      filterable
      remote
      allow-create
      default-first-option
      placeholder="请输入关键词"
      :remote-method="remoteMethod"
      :loading="loading"
    >
      <el-option-group
        v-for="group in groupWords"
        :key="group.label"
        :label="group.label"
      >
        <el-option
          v-for="item in group.options"
          :key="item.text"
          :label="item.text"
          :value="item.text"
        />
      </el-option-group>
    </el-select>
  </div>
</template>

<script>
export default {
  name: 'KeywordSelect',
  props: {
    value: {
      type: Array,
      default: () => {
        return []
      }
    }
  },
  data() {
    return {
      options: [],
      hots: [],
      keywords: [],
      list: [],
      loading: false,
      ruleForm: {
        title: '',
        map_id: 301,
        link: ''
      }
    }
  },
  computed: {
    words() {
      return this.value
    },
    linkHint() {
      return this.linkHints.find(item => {
        return item.type === this.ruleForm.map_id
      })
    },
    groupWords() {
      var data = []
      if (this.options.length > 0) {
        data.push({
          label: '搜索结果',
          options: this.options
        })
      }
      if (this.hots.length > 0) {
        data.push({
          label: '热搜词',
          options: this.hots
        })
      }
      return data
    }
  },
  watch: {
    keywords: {
      handler(v) {
        this.onEmitInput(v)
      },
      deep: true
    },
    value: {
      handler(v) {
        this.keywords = v
      },
      deep: true
    }
  },
  mounted() {
    this.keywords = this.value
    this.getData()
  },
  methods: {
    remoteMethod(query) {
      if (query !== '') {
        this.getData(query)
      } else {
        this.options = []
      }
    },
    getData(word = '') {
      this.loading = true
      this.$http.assemble
        .keyword({
          keyword: word
        })
        .then(
          response => {
            const { data } = response
            if (!word) {
              this.hots = data
            } else {
              this.options = data
            }
            this.loading = false
          },
          error => {
            console.log(error)
            this.loading = false
          }
        )
    },
    onEmitInput(data) {
      this.$emit('input', data)
    }
  }
}
</script>

<style lang="scss" scoped>
.el-select {
  display: block;
}
</style>
